// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <cmath>
#include <vector>
#include <pollux/common/base/exceptions.h>

namespace kumo::pollux::common::hll {
    constexpr double kLowestMaxStandardError = 0.0040625;
    constexpr double kHighestMaxStandardError = 0.26000;
    constexpr double kDefaultApproxDistinctStandardError = 0.023;
    constexpr double kDefaultApproxSetStandardError = 0.01625;

    const int8_t kPrestoSparseV2 = 2;
    const int8_t kPrestoDenseV2 = 3;

    inline void checkMaxStandardError(double error) {
        POLLUX_USER_CHECK_GE(
            error,
            kLowestMaxStandardError,
            "Max standard error must be in [{}, {}] range",
            kLowestMaxStandardError,
            kHighestMaxStandardError);
        POLLUX_USER_CHECK_LE(
            error,
            kHighestMaxStandardError,
            "Max standard error must be in [{}, {}] range",
            kLowestMaxStandardError,
            kHighestMaxStandardError);
    }

    inline int8_t toIndexBitLength(double maxStandardError) {
        int buckets = std::ceil(1.0816 / (maxStandardError * maxStandardError));
        return 8 * sizeof(int) - __builtin_clz(buckets - 1);
    }

    /// Returns first 'indexBitLength' bits of a hash.
    inline uint32_t computeIndex(uint64_t hash, int indexBitLength) {
        return hash >> (64 - indexBitLength);
    }

    /// Returns number of contiguous zeros after 'indexBitLength' bits in the
    /// 'hash'.
    inline int numberOfLeadingZeros(uint64_t hash, int indexBitLength) {
        // Place a 1 in the LSB to preserve the original number of leading zeros if
        // the hash happens to be 0.
        return __builtin_clzl(
            (hash << indexBitLength) | (1L << (indexBitLength - 1)));
    }

    /// Estimates cardinality using Linear Counting algorithm.
    inline double linearCounting(int zeroBuckets, int totalBuckets) {
        return totalBuckets * std::log(totalBuckets * 1.0 / zeroBuckets);
    }
} // namespace kumo::pollux::common::hll
